import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) {
        try {
            //创建一个连接服务器端口9900请求的Socket
            Socket client=new Socket("localhost",9900);
            //连接成功后提示输入
            System.out.println("请输入您的名称:");
            //通过Scanner实现从控制台输入
            // 注意需要将参数System.in传入，表示标准输入-从控制台输入
            Scanner sc=new Scanner(System.in);
            String name=sc.nextLine();

            //获得与服务器端通信的输出流对象，准备向服务器端发送姓名
            OutputStream os=client.getOutputStream();
            //将最基础的OutputStream包装成对象流
            ObjectOutputStream oos=new ObjectOutputStream(os);
            //调用对象流的writeObject方法向服务器端发送姓名
            oos.writeObject(name);

            //获得与服务器端通信的输入流对象，准备接收服务器端的消息
            InputStream is=client.getInputStream();
            //将最基础的InputStream包装成对象流
            ObjectInputStream ois=new ObjectInputStream(is);
            //调用对象流的readObject()获得服务器端发送的消息
            //并在控制台输出
            System.out.println(ois.readObject());
            new Thread(){
                @Override
                public void run() {
                    while (true) {
                        String msg = sc.nextLine();
                        try {
                            oos.writeObject(msg);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }.start();
            new Thread(){
                @Override
                public void run() {
                    while (true) {
                        String msg = null;
                        try {
                            msg = (String) ois.readObject();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } catch (ClassNotFoundException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println(msg);
                    }
                }
            }.start();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
